<?php
/*
 * Created on 20 mars 2009
 * Created by Ludovic Reenaers
 * lreenaers@hotmail.com
 */

 class ProfileDAO extends DAO{
 	private $Bean;
 	
 	function getById($id){
		//return a Profile with a given id
		try
		{
				$query="select * from user_profile where id=$id;";
				$statement=$this->pdo->query($query);
				$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
				foreach($array_obj as $Bean){
					
					$this->Bean = new Profile((int)$Bean->id);
					
					$this->Bean->setName($Bean->name);
					$this->Bean->setDisabled((bool)$Bean->disabled);
					$DAO=$this->factory->getTokenDAO();
					$query="select * from token_fk_profile where profile=$Bean->id;";
					$statement=$this->pdo->query($query);
					$array_fk=$statement->fetchAll(PDO::FETCH_OBJ);
					$tokens = Array();
					foreach($array_fk as $tok){
						array_push($tokens,$DAO->getById((int)$tok->token));
					}
					
					$this->Bean->setTokens($tokens);
				}
		}
		catch(Exception $e)	{
			throw $e;
			}
		
		return $this->Bean;
	}
	function getByName($name){
		//return a Profile with a given id
		try
		{
				$query="select * from user_profile where lower(name)='$name';";
				$statement=$this->pdo->query($query);
				$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
				foreach($array_obj as $Bean){
					
					$this->Bean = new Profile((int)$Bean->id);
					
					$this->Bean->setName($Bean->name);
					$this->Bean->setDisabled((bool)$Bean->disabled);
					$DAO=$this->factory->getTokenDAO();
					$query="select * from token_fk_profile where profile=$Bean->id;";
					$statement=$this->pdo->query($query);
					$array_fk=$statement->fetchAll(PDO::FETCH_OBJ);
					$tokens = Array();
					foreach($array_fk as $tok){
						array_push($tokens,$DAO->getById((int)$tok->token));
					}
					
					$this->Bean->setTokens($tokens);
				}
		}
		catch(Exception $e)	{
			throw $e;
			}
		
		return $this->Bean;
	}
	
	function remove($Bean){
		try{
			$query="delete from token_fk_profile where profile=".$Bean->getId().";";
			$this->pdo->exec($query);
			$bool=true;	
		}catch(Exception $e)	{
			$bool=false;
			$this->pdo->rollBack();
			}
		try{
			$query="update user_profile set disabled=true where id=".$Bean->getId().";";
			$this->pdo->exec($query);
			$bool=true;	
		}catch(Exception $e)	{
			$bool=false;
			$this->pdo->rollBack();
			}
		return $bool;
			
	}
 }
?>
